$(function(){
	
	//检查是否已经登录
	
	$.ajax({
		url: "customer/isLogin.action",
		type: "post",
		success: function(data) {
			if (data.success == "true") {
				//已经登录
				var redirect = getQueryString("redirect");
				if (redirect == null) {
					redirect = 'index.jsp';
				}
				window.location.href = redirect;
			}
		},
		error: function() {
			toastr.error("获取登录信息发生错误，请联系管理员");
		}
	});
	validateInit();
})

function validateInit() {
	    
    $("#loginForm").validate({                   
        rules:{
            customerName:{
                required: true
            },
            customerPassword:{
                required: true,
                minlength: 6,
                maxlength: 16
            }
        },
        
        // Messages for form validation
        messages:
        {
        	customerName:{
                required: '用户名不能为空'
            },
            customerPassword:{
                required: '密码不能为空',
				maxlength: $.validator.format( "密码长度必须小于 {0} 位" ),
				minlength: $.validator.format( "密码长度必须大于 {0} 位" )
            }
        },                  
        
        // Do not change code below
        errorPlacement: function(error, element) {
            error.insertAfter(element.parent());
        }
    });
}

function login() {
	if (!$("#loginForm").valid()) {
		return;
	}
	var redirect = getQueryString("redirect");
	if (redirect == null) {
		redirect = 'index.jsp';
	}
	$.ajax({
		url: "customer/login.action",
		type: "post",
		data: $("#loginForm").serialize(),
		success: function(data) {
			if (data.success == "true") {
				window.location.href = redirect;
			} else if (data.success == "false") {
				toastr.error("用户名或密码错误");
			} else {
				toastr.error("后台处理发生错误，请联系管理员");
			}
		},
		error: function() {
			toastr.error("提交请求发生错误，请联系管理员");
		}
	});
}

